import socket
import struct

if __name__ == '__main__':
    tcp_client_socket = socket.socket()
    tcp_client_socket.connect(("127.0.0.1", 9001))
    name = ""

    def yo():
        name = input("请输入你的姓名20以内")
        if len(name) > 20:
            print("姓名过长请输入内容80以内请重新输入")
            yo()
        name = name.encode("utf-8")
        # 内容
        message = input("输出内容")
        if len(message) > 80:
            print("内容过长请重新输入")
            yo()
        message = message.encode("utf-8")
        return name, message


    while True:
        name, message = yo()
        values = (len(name), len(message), name, message)
        s = struct.Struct(f'BI{len(name)}s{len(message)}s')
        # 打包
        packed_data = s.pack(*values)
        # 发送
        tcp_client_socket.send(packed_data)

        recv_data = tcp_client_socket.recv(128)
        s1 = struct.unpack('I', recv_data[0:4])
        s2 = struct.unpack('I', recv_data[4:8])
        byProtocol, all_len, name, message = struct.unpack(f'BI{s1[0]}s{s2[0]}s', recv_data)
        print(
            f"采用协议{byProtocol},传输数据总长度{len(s1) + len(s2)},姓名:{name.decode('utf-8').split(',')[0]},说:{message.decode('utf-8')}")
